package sentinel

import (
	"gc-rds-ha/internal/dao"

	log "github.com/sirupsen/logrus"
	"golang.org/x/net/context"

	"gorm.io/gorm"
)

type MysqlProxyFailRecord struct {
	dao.DefaultField

	ProxyIP          string `gorm:"type:varchar(200);not null;default:'';comment:proxy节点ID，对应ecs实例ID;"`
	VipIP            string `gorm:"type:varchar(200);not null;default:'';comment:绑定的vip地址;"`
	FailNum          uint32 `gorm:"type:tinyint(3);not null;default:0;comment:哨兵检测的失败次数;"`
	Status           uint32 `gorm:"type:tinyint(3);not null;default:1;comment:1主观下线 2客观下线;"`
	IsChangeBind     uint32 `gorm:"type:tinyint(3);not null;default:1;comment:1是 2否;"`
	ChangBindProxyIp string `gorm:"type:varchar(200);not null;default:'';comment:换绑后的vip地址;"`
	SentinelOpAddr   string `gorm:"type:varchar(200);not null;default:'';comment:操作的sentinel地址;"`

	Tx *gorm.DB `gorm:"-"`
}

func (d *MysqlProxyFailRecord) Model() *gorm.DB {
	db := dao.DB
	if d.Tx != nil {
		db = d.Tx
	}
	return db.Table(d.TableName()).Model(d)
}

func (d *MysqlProxyFailRecord) TableName() string {
	tableName := "mysql_proxy_fail_record"
	return tableName
}

// Create 创建
func (d *MysqlProxyFailRecord) Create(ctx context.Context) error {
	if err := d.Model().Create(d).Error; err != nil {
		log.WithFields(log.Fields{"err": err, "d": d}).Error("MysqlProxyFailRecord m.Create(d) error")
	}

	return nil
}

func CreateTableMysqlProxyFailRecord() {
	d := &MysqlProxyFailRecord{}
	for i := uint32(0); i < d.TableCount(); i++ {
		if err := dao.DB.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(d); err != nil {
			log.WithField("", log.Fields{"err": err, "tableName": d.TableName()}).Error("DB AutoMigrate Failed")
		}
	}
}

func (d *MysqlProxyFailRecord) List(offset, limit int) ([]MysqlProxyFailRecord, error) {
	var l = make([]MysqlProxyFailRecord, 10)
	m := d.Model()
	if d.ID >= 0 {
		m = m.Where("id", d.ID)
	}

	if err := m.Order("id desc").Offset(offset).Limit(limit).Find(&l).Error; err != nil {
		log.WithFields(log.Fields{
			"d":     d,
			"error": err,
		}).Error("MysqlProxyFailRecord.List error: ")
		return nil, err
	}
	return l, nil
}

// TableCount 分表数量
func (d *MysqlProxyFailRecord) TableCount() uint32 {
	return 1
}
